package com.estore.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.estore.converter.DateTime;
import com.estore.entity.AgentBanner;
import com.estore.entity.Agent_Product;
import com.estore.entity.Agent_Profile;
import com.estore.entity.Discount;
import com.estore.entity.ProductList;
import com.estore.entity.Product_Image;
import com.estore.entity.ShopInterface;
import com.estore.info.AgentProductInfo;
import com.estore.info.ProductInfo;
import com.estore.info.ShopInfo;
import com.estore.info.SubCatInfo;
import com.estore.manager.ProductManager;
import com.estore.manager.ShopManager;
import com.estore.model.ProductModel;
import com.estore.model.ShopModel;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ShopAction extends ActionSupport implements
		ModelDriven<ShopModel>, ServletRequestAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5711173603024575441L;
	ShopModel shopModel = new ShopModel();
	ProductModel productModel = new ProductModel();
	private boolean searchType;

	public boolean isSearchType() {
		return searchType;
	}

	public void setSearchType(boolean searchType) {
		this.searchType = searchType;
	}

	ShopManager shopManager;
	ProductManager productManager;


	private List<SubCatInfo> listSubCat;

	DateTime dateTime = new DateTime();
	public HttpServletRequest request;

	public String searchAgentName() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			String agentName = shopModel.getAgentName();
			searchType = shopModel.isSearchType();
			shopModel.setSearchAgentMessage(agentName);
			List<Agent_Profile> listAgent = shopManager.searchAgentByAgentName(agentName, searchType);
			shopModel.setListAgent(listAgent);
			listSubCat = productManager.listSubCatInfo();
			shopModel.setAgentName("");
			shopModel.setSearchType(false);
			return SUCCESS;
		} else {
			return "banned";
		}
	}
	
	public String searchProductOfShop() {
		Integer agentID = shopModel.getAgentID();
		System.out.println(agentID);
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			String searchText = shopModel.getSearchText();
			if (searchText != null) {
				if(searchText.equals("")){
					List<ProductInfo> listProduct = productManager.getAllProduct(1);
					List<ProductInfo> listProductResult = new ArrayList<ProductInfo>();
					for(ProductInfo record : listProduct){
						ProductList productList = shopManager.getProductList(Integer.parseInt(record.getProductID()), agentID);
						if(productList != null){
							Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
							record.setSellingPrice(agentProduct.getSellingPrice());
							record.setListID(productList.getListID());
							listProductResult.add(record);
						}
					}
					shopModel.setListProduct(listProductResult);
					setListSubCat(productManager.listSubCatInfo());
					shopModel.setShopInterface(shopManager.getShopInterface(agentID));
					shopModel.setSearchText("");
					shopModel.setAgentID(agentID);
					return "fullsearch";
				}
				List<ProductInfo> listFullTextSearchResult = new ArrayList<ProductInfo>();
				List<ProductInfo> listExactlyResult = new ArrayList<ProductInfo>();
				List<ProductInfo> listFullTextSearch = shopManager.listFullTextSearchResultForShop(searchText, agentID);
				for(ProductInfo record : listFullTextSearch){
					ProductList productList = shopManager.getProductList(Integer.parseInt(record.getProductID()), agentID);
					Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
					Discount discount = shopManager.getDiscount(productList.getListID());
					if(agentProduct != null){
						record.setSellingPrice(agentProduct.getSellingPrice());
					}
					if(discount != null){
						record.setDiscount(discount.getDiscount());
						float discountPercent = Math.round((float)((((float)agentProduct.getSellingPrice() - (float)discount.getDiscount())  / 
								(float)agentProduct.getSellingPrice())) * 100);
						record.setDiscountPercent(discountPercent);
					}
					record.setListID(productList.getListID());
					listFullTextSearchResult.add(record);
				}
				List<ProductInfo> listExactly = shopManager.listExactlyResultForShop(searchText, agentID);
				for(ProductInfo record : listExactly){
					ProductList productList = shopManager.getProductList(Integer.parseInt(record.getProductID()), agentID);
					Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
					Discount discount = shopManager.getDiscount(productList.getListID());
					if(agentProduct != null){
						record.setSellingPrice(agentProduct.getSellingPrice());
					}
					if(discount != null){
						record.setDiscount(discount.getDiscount());
						float discountPercent = Math.round((float)((((float)agentProduct.getSellingPrice() - (float)discount.getDiscount())  / 
								(float)agentProduct.getSellingPrice())) * 100);
						record.setDiscountPercent(discountPercent);
					}
					record.setListID(productList.getListID());
					listExactlyResult.add(record);
				}
				shopModel.setFullTextResult(listFullTextSearchResult);
				shopModel.setExactlyResult(listExactlyResult);
				shopModel.setFullTextResultSize(listFullTextSearchResult.size());
				shopModel.setExactlyResultSize(listExactlyResult.size());
				if(listExactlyResult.isEmpty()){
					shopModel.setExactlyResultEmpty("Không có kết quả cho từ khóa: ");
				}
				shopModel.setTextDisplayOnSearch(searchText);
			}
			setListSubCat(productManager.listSubCatInfo());
			shopModel.setSearchText("");
			shopModel.setShopInterface(shopManager.getShopInterface(agentID));
			shopModel.setListBanner(shopManager.listAgentBanner(agentID));
			shopModel.setAgentID(agentID);
			return SUCCESS;
		} else {
			return "banned";
		}
	}
	
	public String editDiscount() throws ParseException {
		shopModel.setMessageMakeDiscount("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					String productID = shopModel.getProductID();
					ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
					ProductList productList = shopManager.getProductList(Integer.parseInt(productID), shopInfo.getAgentID());
					Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
					Discount discount = shopModel.getDiscount();
					discount.setListID(productList.getListID());
					if(discount.getDiscount() == null){
						shopModel.setMessageMakeDiscount("Vui lòng điền giá");
					}else{
						if(discount.getDiscount() >= agentProduct.getSellingPrice() ){
							shopModel.setMessageMakeDiscount("Giá khuyến mãi không được lớn hơn hoặc bằng giá hiện tại");
						}else{
							shopManager.editDiscount(discount);
							shopModel.setMessageMakeDiscount("Thay đổi giá khuyến mại thành công");
						}
					}
					
					// set product infomation
					shopModel.setAgentProductInfo(agentProduct);
					shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productID), 0));
					// set current discount infomation
					Discount currentDiscount = shopManager.getDiscount(productList.getListID());
					shopModel.setDiscount(currentDiscount);
					shopModel.setAgentProductInfo(agentProduct);
					shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productID), 0));
					
					Integer dayLeft = dateTime.dayLeft(currentDiscount.getEndDate());
					shopModel.setDiscountTimeLeft(dayLeft);
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String endDiscount(){
		shopModel.setMessageMakeDiscount("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
					String productID = request.getParameter("productID");
					ProductList productList = shopManager.getProductList(Integer.parseInt(productID), shopInfo.getAgentID());
					shopManager.endDiscount(productList.getListID());
					
					// reload data for product management page of shop
					List<ProductList> listShopProduct = shopManager.getAllProductOfShop(shopInfo.getAgentID());
					List<ProductInfo> listProduct = new ArrayList<ProductInfo>();
					for (ProductList record : listShopProduct) {
						ProductInfo productInfo = new ProductInfo();
						Integer listType = record.getListType();
						// get product info of shop
						Agent_Product agentProduct = shopManager.getAgentProductInfo(record.getListID());
						// get discount if have
						Discount discount = shopManager.getDiscount(record.getListID());
						// set product info of web or shop
						if (listType == 0) {
							productInfo = productManager.getProductInfo(record.getProductID(), 0);
						} else {
							productInfo = productManager.getProductInfo(record.getProductID(), productList.getAgentID());
						}
						// set discount if have
						if(discount != null){
							productInfo.setDiscount(discount.getDiscount());
							float discountPercent = Math.round((float)((((float)agentProduct.getSellingPrice() - (float)discount.getDiscount())  / 
									(float)agentProduct.getSellingPrice())) * 100);
							productInfo.setDiscountPercent(discountPercent);
						}
						productInfo.setSellingPrice(agentProduct.getSellingPrice());
						productInfo.setWarranty(agentProduct.getWarranty());
						productInfo.setCondition(agentProduct.getProductCondition());
						productInfo.setStartDate(agentProduct.getStartDate());
						productInfo.setListID(agentProduct.getListID());
						listProduct.add(productInfo);
					}
					productModel.setListProduct(listProduct);
					
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String makeDiscount() throws ParseException {
		shopModel.setMessageMakeDiscount("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					String productID = shopModel.getProductID();
					String duration = shopModel.getDuration();
					ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
					ProductList productList = shopManager.getProductList(Integer.parseInt(productID), shopInfo.getAgentID());
					Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
					// set product infomation
					shopModel.setAgentProductInfo(agentProduct);
					shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productID), 0));
					Discount discount = shopModel.getDiscount();
					discount.setListID(productList.getListID());
					if(discount.getDiscount() == null){
						shopModel.setMessageMakeDiscount("Vui lòng điền giá");
					}else{
						if(discount.getDiscount() >= agentProduct.getSellingPrice() ){
							shopModel.setMessageMakeDiscount("Giá khuyến mãi không được lớn hơn hoặc bằng giá hiện tại");
						}else{
							if(shopManager.checkDiscountAvailable(productList.getListID())){
								shopModel.setMessageMakeDiscount("Sản phẩm hiện đã có khuyến mại");
							}else{
								shopManager.makeDiscount(discount, Integer.parseInt(duration));
								shopModel.setMessageMakeDiscount("Đăng khuyến mại thành công");
							}
						}
					}
					
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String changeShopProductInfo() {
		shopModel.setEditProductInfoMessage("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					AgentProductInfo agentProduct = shopModel.getAgentProduct();
					if(shopModel.getAgentProduct().getSellingPrice() == null || shopModel.getAgentProduct().getWarranty().equals("")){
						shopModel.setEditProductInfoMessage("Vui lòng điền đầy đủ giá và thời hạn bảo hành");
						return SUCCESS;
					}else{
						shopManager.changeProductInfo(agentProduct);
						shopModel.setEditProductInfoMessage("Thay đổi thông tin sản phẩm thành công");
						shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(shopModel.getProductID()), 0));
					}
					shopModel.setAgentProduct(null);
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String addShopBanner() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInterface shopInterface = shopModel.getShopInterface();
					Integer agentID = shopInterface.getAgentID();
					
					List<File> fileUpload = shopModel.getImgUpload();
					List<String> fileUploadName = shopModel.getImgUploadFileName();
					List<String> listFileName = new ArrayList<String>();
					DateTime dateTime = new DateTime();
					if (fileUpload != null && fileUploadName != null) {
						for (int i = 0; i < fileUpload.size(); i++) {
							String fileName = dateTime.addImgDate() + fileUploadName.get(i);
							String contextPath = request.getRealPath("/");
							String path = contextPath + "img/banner/" + fileName;
							listFileName.add("img/banner/" + fileName);
							try {
								File f = new File(path);
								BufferedImage originalImage = ImageIO.read(fileUpload.get(i));
//								int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
//								BufferedImage resizeImage = ImageResize.resizeImage(originalImage, type);
								ImageIO.write(originalImage, "jpg", f);
							} catch (IOException e) {
								System.out.println(e.getMessage());
							}
						}
						List<String> listName = new ArrayList<String>();
						for (String record : listFileName) {
							boolean check = true;
							for (String record1 : listName) {
								if (record.equals(record1)) {
									check = false;
								}
							}
							if (check == true) {
								listName.add(record);
							}
						}
						shopManager.addShopBanner(agentID, listName);
					}


					shopModel.setImgUpload(null);
					shopModel.setImgUploadFileName(null);
					
					// set banner for banner management page
					if(shopManager.listAgentBanner(agentID) != null){
						shopModel.setListBanner(shopManager.listAgentBanner(agentID));
						int emptyBanner = 5;
						List<AgentBanner> listBanner = shopManager.listAgentBanner(agentID);
						for(AgentBanner record : listBanner){
							emptyBanner -= 1;
						}
						List<String> listEmptyBanner = new ArrayList<String>();
						for(int i =0; i < emptyBanner; i ++){
							listEmptyBanner.add("a");
						}
						shopModel.setListEmptyBanner(listEmptyBanner);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String editTittleBanner() {
		shopModel.setErrorTitleBanner("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					AgentBanner banner = shopModel.getAgentBanner();
					if(banner.getLinkBanner().equals(0)){
						shopModel.setErrorTitleBanner("Vui lòng chọn banner");
					}else {
						if(banner.getTittle1().equals("") || banner.getTittle2().equals("")){
							shopModel.setErrorTitleBanner("Vui lòng điền đầy đủ tittle");
						}else{
							List<AgentBanner> listBanner = shopManager.listAgentBanner(banner.getAgentID());
							// get location of title
							int i = 1;
							int size = 1;
							for(AgentBanner record : listBanner){
								if(record.getLinkBanner().equals(banner.getLinkBanner())){
									i = size;
								}
								size ++ ;
							}
							// split list String title 1 
							String[] tokens = banner.getTittle1().split(",");
							List<String> listTittle1 = new ArrayList<String>();
							for(String record : tokens){
								if(record.trim().equals("")){
									listTittle1.add("");
								}else{
									listTittle1.add(record.trim());
								}
							}
							banner.setTittle1(listTittle1.get(i-1));
							// split list String tittle 2
							tokens = banner.getTittle2().split(",");
							List<String> listTittle2 = new ArrayList<String>();
							for(String record : tokens){
								if(record.trim().equals("")){
									listTittle2.add("");
								}else{
									listTittle2.add(record.trim());
								}
							}
							banner.setTittle2(listTittle2.get(i-1));
							
							// set banner title
							shopManager.setBannerTittle(banner);
							
							// message set title success
							shopModel.setErrorTitleBanner("Thay đổi tittle thành công");
						}
					}
					if(shopManager.listAgentBanner(banner.getAgentID()) != null){
						shopModel.setListBanner(shopManager.listAgentBanner(banner.getAgentID()));
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String editProductType() {
		shopModel.setErrorProductInfo("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInterface shopInterface = shopModel.getShopInterface();
					System.out.println(shopInterface.getProductList());
					System.out.println(shopInterface.getAgentID());
					if (shopInterface != null) {
						shopManager.editProductType(shopInterface);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String editTemplate() {
		shopModel.setErrorProductInfo("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInterface shopInterface = shopModel.getShopInterface();
					if (shopInterface != null) {
						shopManager.editTemplate(shopInterface);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}
	
	public String editCategoriesBar() {
		shopModel.setErrorProductInfo("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInterface shopInterface = shopModel.getShopInterface();
					if (shopInterface != null) {
						shopManager.editCategoriesBar(shopInterface);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String editBanner() {
		shopModel.setErrorProductInfo("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					ShopInterface shopInterface = shopModel.getShopInterface();
					if (shopInterface != null) {
						shopManager.editBanner(shopInterface);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String shopDetailByMod() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {

			if (session.get("role") == null) {
				return "login";
			} else if (session.get("role").equals(1) || session.get("role").equals(3)) {
				Integer agentID = Integer.parseInt(request.getParameter("agentID"));
				if (agentID != null) {
					shopModel.setShopInfo(shopManager.getShopInfoByAgentID(agentID));
				}
				return SUCCESS;
			} else {
				return ERROR;
			}
		} else {
			return "banned";
		}
	}

	public String saleProduct() throws ParseException {
		shopModel.setMessageAddShopProduct("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
		if (session.get("isBanned") == null || session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					try {
						shopModel.getProductInfo().getProductID();
						shopModel.getAgentProduct().getSellingPrice();
						shopModel.getAgentProduct().getWarranty();
					} catch (Exception e) {
						List<ProductInfo> listProduct = productManager.getAllProduct(1);
						List<ProductInfo> listProductInfo = new ArrayList<ProductInfo>();
						for(ProductInfo record : listProduct){
							if(shopManager.getProductList(Integer.parseInt(record.getProductID()), shopInfo.getAgentID()) != null){
								record.setListID(shopManager.getProductList(Integer.parseInt(record.getProductID()), 
										shopInfo.getAgentID()).getListID());
							}
							listProductInfo.add(record);
						}
						productModel.setListProduct(listProductInfo);
						return "productIDNull";
					}
						
					if (shopModel.getProductInfo() != null) {
							
							ProductInfo productInfo = shopModel.getProductInfo();
								try {
									int price = shopModel.getAgentProduct().getSellingPrice();
									int warranty = shopModel.getAgentProduct().getWarranty();
								} catch (Exception e) {
									shopModel.setMessageAddShopProduct("Vui lòng điền đầy đủ thông tin đăng bán");
									shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productInfo.getProductID()), 0));
									return "errorInfo";
								}
							if(shopModel.getAgentProduct().getSellingPrice() == null || 
									shopModel.getAgentProduct().getWarranty() == null){
								shopModel.setMessageAddShopProduct("Vui lòng điền đầy đủ thông tin đăng bán");
								shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productInfo.getProductID()), 0));
								return "errorInfo";
							}
							if (shopManager.checkListAvail(Integer.parseInt(productInfo.getProductID()),shopInfo.getAgentID())) {
								return "listAvail";
							}
							List<File> fileUpload = shopModel.getImgUpload();
							List<String> fileUploadName = shopModel.getImgUploadFileName();
							if(fileUploadName != null){
								if(fileUploadName.size() > 5){
									shopModel.setMessageAddShopProduct("Bạn chỉ được đăng tối đa 5 hình ảnh");
									return SUCCESS;
								}
							}
							List<String> listFileName = new ArrayList<String>();
							DateTime dateTime = new DateTime();
							if (fileUpload != null && fileUploadName != null) {
								for (int i = 0; i < fileUpload.size(); i++) {
									String fileName = dateTime.addImgDate()+ fileUploadName.get(i);
									String contextPath = request.getRealPath("/");
									String path = contextPath + "img/" + fileName;
									listFileName.add("img/" + fileName);
									try {
										File f = new File(path);
										BufferedImage originalImage = ImageIO.read(fileUpload.get(i));
//									int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
//									BufferedImage resizeImage = ImageResize.resizeImage(originalImage, type);
										ImageIO.write(originalImage, "jpg", f);
										// FileUtils.copyFile(fileUpload.get(i), f);
									} catch (IOException e) {
										System.out.println(e.getMessage());
									}
								}
								List<String> listName = new ArrayList<String>();
								for (String record : listFileName) {
									boolean check = true;
									for (String record1 : listName) {
										if (record.equals(record1)) {
											check = false;
										}
									}
									if (check == true) {
										listName.add(record);
									}
								}
								List<Product_Image> listProductImg = new ArrayList<Product_Image>();
								Integer imgType = null;
								if (session.get("role").equals(1)
										|| session.get("role").equals(2)) {
									imgType = 0;
								} else if (session.get("role").equals(5)) {
									imgType = shopInfo.getAgentID();
								}
								for (String record : listName) {
									Product_Image productImg = new Product_Image();
									productImg.setProductID(Integer.parseInt(productInfo.getProductID()));
									productImg.setMainImg(0);
									productImg.setLinkImg(record);
									productImg.setImgType(imgType);
									listProductImg.add(productImg);
								}
								productManager.addNewImg(listProductImg);
								if (!productManager.checkMainImg(productInfo.getProductID(), imgType.toString())) {
									productManager.setMainImg(productInfo.getProductID(), imgType.toString());
								}
							}
							
							if (shopModel.getAgentProduct() != null) {
								Integer saleType = shopModel.getSaleType();
								AgentProductInfo info = shopModel.getAgentProduct();
								shopManager.addProductInfoByShop(Integer.parseInt(productInfo.getProductID()), 
										info, saleType, shopInfo.getAgentID());
							}

						shopModel.setImgUpload(null);
						shopModel.setImgUploadFileName(null);
						// get product detail
						ProductList productList = shopManager.getProductList(Integer.parseInt(productInfo.getProductID())
								, shopInfo.getAgentID());
						ProductInfo productInfo1 = new ProductInfo();
						Discount discount = new Discount();
						// check if shop using product information of website or shop
						if(productList.getListType() == 0){
							productInfo1 = productManager.getProductInfo(productList.getProductID(), 0);
						}else{
							productInfo1 = productManager.getProductInfo(productList.getProductID(), productList.getAgentID());
						}
						Agent_Product agentProduct = shopManager.getAgentProductInfo(productList.getListID());
						if(shopManager.getDiscount(productList.getListID()) != null){
							discount = shopManager.getDiscount(productList.getListID());
							float discountPercent = Math.round((float)((((float)agentProduct.getSellingPrice() - (float)discount.getDiscount())  / 
									(float)agentProduct.getSellingPrice())) * 100);
							discount.setDiscountPercent(discountPercent);
							Integer dayLeft = dateTime.dayLeft(discount.getEndDate());
							shopModel.setDiscountTimeLeft(dayLeft);
							shopModel.setDiscount(discount);
						}
						productInfo1.setListType(productList.getListType());
						shopModel.setProductInfo(productInfo1);
						shopModel.setAgentProductInfo(agentProduct);
						shopModel.setAgentID(productList.getAgentID());
						shopModel.setShopInterface(shopManager.getShopInterface(productList.getAgentID()));
					}
					shopModel.setAgentProduct(null);
					shopModel.setProductInfo(null);
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String confirmSaleType() {
		shopModel.setErrorProductInfo("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					if (shopModel.getProductInfo() != null) {
						ProductInfo info = shopModel.getProductInfo();
						ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
						if (shopManager.checkListAvail(Integer.parseInt(info.getProductID()), shopInfo.getAgentID())) {
							return "listAvail";
						}
						shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(info.getProductID()), 0));
					}

					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String saleLink() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					String productID = request.getParameter("productID");
					if (productID != null) {
						shopModel.setProductInfo(productManager.getProductInfo(Integer.parseInt(productID), 0));
						ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
						if (shopManager.checkListAvail(Integer.parseInt(productID), shopInfo.getAgentID())) {
							return "listAvail";
						}
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String updateLogo() {
		shopModel.setErrorProfile("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {

					List<String> listFileName = new ArrayList<String>();
					List<File> fileUpload = shopModel.getImgUpload();
					String fileName = "";
					List<String> fileUploadName = shopModel.getImgUploadFileName();
					if (fileUpload != null) {
						for (int i = 0; i < fileUpload.size(); i++) {
							fileName = dateTime.addImgDate() + fileUploadName.get(i);
							String contextPath = request.getRealPath("/");
							String path = contextPath + "img/shopLogo/" + fileName;
							listFileName.add("img/shopLogo/" + fileName);
							try {
								File f = new File(path);
								BufferedImage originalImage = ImageIO.read(fileUpload.get(i));
//								int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
//								BufferedImage resizeImage = ImageResize.resizeImage(originalImage, type);
								ImageIO.write(originalImage, "jpg", f);
								// FileUtils.copyFile(fileUpload.get(i), f);
							} catch (IOException e) {
								System.out.println(e.getMessage());
							}
							String linkAvatar = "";
							for (String record : listFileName) {
								linkAvatar = record;
							}
							ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
							Integer agentID = shopInfo.getAgentID();
							shopManager.updateLogo(linkAvatar, agentID);
							shopInfo.setLogo(linkAvatar);
							session.put("shopInfo", shopInfo);
							shopModel.setImgUpload(null);
							shopModel.setImgUploadFileName(null);
						}
					} else {
						shopModel.setErrorProfile("Bạn chưa chọn ảnh");
					}

					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String changeShopProfile() {
		shopModel.setErrorProfile("");
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("isBanned") == null
				|| session.get("isBanned").equals(0)) {
			if (session.get("role") == null) {
				return "login";
			} else {
				if (session.get("shop").equals("Avail")) {
					boolean check = true;
					ShopInfo info = shopModel.getShopInfo();
					if (info.getAgentEmail().equals("") || info.getAddress().equals("")
							|| info.getPhoneNumber().equals("") || info.getAgentWebsite().equals("")) {
						check = false;
						shopModel.setErrorProfile("Xin vui lòng điền đẩy đủ thông tin");
						shopModel.setShopInfo(null);
						return SUCCESS;
					}
					ShopInfo shopInfo = (ShopInfo) session.get("shopInfo");
					if (shopManager.checkEmailAvail(info.getAgentEmail())
							&& !(info.getAgentEmail().equals(shopInfo.getAgentEmail()))) {
						check = false;
						if (shopModel.getErrorProfile().equals("")) {
							shopModel.setErrorProfile("Email đã được sử dụng");
							shopModel.setShopInfo(null);
						}
					}
					if (check == true) {
						info.setAgentID(shopInfo.getAgentID());
						shopManager.changeShopProfile(info);
						shopInfo.setAddress(info.getAddress());
						shopInfo.setPhoneNumber(info.getPhoneNumber());
						shopInfo.setAgentEmail(info.getAgentEmail());
						shopInfo.setAgentWebsite(info.getAgentWebsite());
						session.put("shopInfo", shopInfo);
						shopModel.setErrorProfile("Đổi thông tin thành công");
						shopModel.setShopInfo(null);
					}
					return SUCCESS;
				} else {
					if(session.get("role").equals(4)){
						return ERROR;
					}else {
						return "homepage";
					}
				}
			}
		} else {
			return "banned";
		}
	}

	public String listAllShop() {
		return "success";
	}

	@Override
	public ShopModel getModel() {
		return shopModel;
	}

	public ShopModel getShopModel() {
		return shopModel;
	}

	public void setShopmodel(ShopModel shopModel) {
		this.shopModel = shopModel;
	}

	public ShopManager getShopManager() {
		return shopManager;
	}

	public void setShopManager(ShopManager shopManager) {
		this.shopManager = shopManager;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}

	public ProductManager getProductManager() {
		return productManager;
	}

	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}

	public DateTime getDateTime() {
		return dateTime;
	}

	public void setDateTime(DateTime dateTime) {
		this.dateTime = dateTime;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setShopModel(ShopModel shopModel) {
		this.shopModel = shopModel;
	}

	public List<SubCatInfo> getListSubCat() {
		return listSubCat;
	}

	public void setListSubCat(List<SubCatInfo> listSubCat) {
		this.listSubCat = listSubCat;
		
	}
	public ProductModel getProductModel() {
		return productModel;
	}

	public void setProductModel(ProductModel productModel) {
		this.productModel = productModel;
	}
}
